<?php

namespace addons\Attend\merchant\controllers;


use Yii;
use yii\helpers\Json;
use yii\db\Expression;
use common\traits\Curd;
use common\models\base\SearchModel;
use common\enums\StatusEnum;
use common\helpers\ExcelHelper;
use addons\Attend\common\enums\CheckEnum;
use addons\Attend\common\models\AttendCheck;
use addons\Attend\common\models\AttendClasses;
use addons\Attend\common\models\AttendPlan;


class CheckController extends BaseController
{
    use Curd;

    public $modelClass = AttendCheck::class;

    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'relations' => ['member' => ['realname'],'attendClasses' => ['title']], // 关联 member 表的 nickname 字段
            'partialMatchAttributes' => ['member.realname','attendClasses.title'], // 模糊查询，注意 member_nickname 为关联表的别名 表名_字段

            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);
        $search = $params = Yii::$app->request->queryParams;
        $created_time = [];
        if(!empty($search['SearchModel']['created_at'])){
            list($start,$end) = explode('/',$params['SearchModel']['created_at']);
            $start = strtotime($start);
            $end = strtotime($end);
            $created_time = ['between',AttendCheck::tableName().'.created_at',$start,$end];
            unset($params['SearchModel']['created_at']);
        }
        $dataProvider = $searchModel->search($params);
//        if(Yii::$app->id == 'merchant'&&Yii::$app->user->identity->role_id!=0)
//            $dataProvider->query
//                ->andWhere(['member_id' => Yii::$app->user->id]);
//        if(Yii::$app->id == 'merchant'&&Yii::$app->user->identity->role_id==0)
//            $dataProvider->query
//                ->andWhere([AttendCheck::tableName().'.merchant_id' => $this->getMerchantId()]);
        !empty($created_time)?$dataProvider->query
            ->andWhere($created_time):$dataProvider->query
            ->andFilterWhere([AttendCheck::tableName().'.merchant_id' => $this->getMerchantId()]);
        if(Yii::$app->id == 'merchant'&&Yii::$app->user->identity->department_id!=0)
            $dataProvider->query
                ->andWhere([AttendCheck::tableName().'.member_id' => Yii::$app->user->id]);

        if(empty($search['SearchModel'])) $search['SearchModel']=['member.realname'=>'','type'=>'','attendClasses.title'=>'','created_at'=>'','state'=>''];
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'search' => $search,

        ]);
    }

    public function actionCreate()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->covers = Json::decode($model->covers);
        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            $check = AttendCheck::find()->andWhere(['member_id' => Yii::$app->user->id,'type'=>$model->type,'classes_id'=>$model->classes_id])->one();
            if($check&&$check->type==0&&date("Y-m-d", $check->created_at)==date("Y-m-d", time()))
                return $this->message("该班次已经签到了，不能重复签到！", $this->redirect(Yii::$app->request->referrer), 'error');
            if($check&&$check->type==1&&date("Y-m-d", $check->created_at)==date("Y-m-d", time()))
                return $this->message("该班次已经签退了，不能重复签退！", $this->redirect(Yii::$app->request->referrer), 'error');

            $where = new Expression("FIND_IN_SET(:supplier, check_date)", [":supplier" => date("Y-m-d", time())]);
            $plans = AttendPlan::find()->andWhere($where)->andWhere(['member_id' => Yii::$app->user->id,'classes_id'=>$model->classes_id])->one();
            if(!$plans)
                return $this->message("没有该班次！", $this->redirect(Yii::$app->request->referrer), 'error');
            else if ((Yii::$app->request->get('type') == CheckEnum::SignIn)) {
                if (strtotime(date("Y-m-d", time()) . ' ' . $plans->begin_time) < time())
                    $model->state = 2;
                else $model->state = 1;
            } else if ((Yii::$app->request->get('type') == CheckEnum::SignOut)) {
                if (strtotime(date("Y-m-d", time()) . ' ' . $plans->end_time) > time())
                    $model->state = 3;
                else $model->state = 1;
            }
            $model->begin_time = $plans->begin_time;
            $model->end_time = $plans->end_time;
            !empty($model->covers) && $model->covers = Json::encode($model->covers);

            $transaction = Yii::$app->db->beginTransaction();
            try {
                $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');

                $transaction->commit();
            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->message("打卡出错啦！", $this->redirect(Yii::$app->request->referrer), 'error');

            }
        }


        return $this->renderAjax('create', [
            'model' => $model,
            'classes' => AttendClasses::getDropDown(),

        ]);

    }
    public function actionEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->covers = Json::decode($model->covers);
        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            $check = AttendCheck::find()->andWhere(['member_id' => Yii::$app->user->id,'type'=>$model->type,'classes_id'=>$model->classes_id])->one();
            if($check&&$check->type==0&&date("Y-m-d", $check->created_at)==date("Y-m-d", time()))
                return $this->message("该班次已经签到了，不能重复签到！", $this->redirect(Yii::$app->request->referrer), 'error');
            if($check&&$check->type==1&&date("Y-m-d", $check->created_at)==date("Y-m-d", time()))
                return $this->message("该班次已经签退了，不能重复签退！", $this->redirect(Yii::$app->request->referrer), 'error');

            $where = new Expression("FIND_IN_SET(:supplier, check_date)", [":supplier" => date("Y-m-d", time())]);
            $plans = AttendPlan::find()->andWhere($where)->andWhere(['member_id' => Yii::$app->user->id,'classes_id'=>$model->classes_id])->one();
            if(!$plans)
                return $this->message("没有该班次！", $this->redirect(Yii::$app->request->referrer), 'error');
            else if ((Yii::$app->request->get('type') == CheckEnum::SignIn)) {
                if (strtotime(date("Y-m-d", time()) . ' ' . $plans->begin_time) < time())
                    $model->state = 2;
                else $model->state = 1;
            } else if ((Yii::$app->request->get('type') == CheckEnum::SignOut)) {
                if (strtotime(date("Y-m-d", time()) . ' ' . $plans->end_time) > time())
                    $model->state = 3;
                else $model->state = 1;
            }
            $model->begin_time = $plans->begin_time;
            $model->end_time = $plans->end_time;
            !empty($model->covers) && $model->covers = Json::encode($model->covers);

            $transaction = Yii::$app->db->beginTransaction();
            try {
                $model->save()
                    ? $this->redirect(['index'])
                    : $this->message($this->getError($model), $this->redirect(['index']), 'error');

                $transaction->commit();
            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->message("打卡出错啦！", $this->redirect(Yii::$app->request->referrer), 'error');

            }
        }
        return $this->renderAjax('edit', [
            'model' => $model,
            'classes' => AttendClasses::getDropDown(),

        ]);

    }
    public function actionDelete($id)
    {
        if ($this->findModel($id)->delete()) {
            return $this->message("删除成功", $this->redirect(['index']));
        }

        return $this->message("删除失败", $this->redirect(['index']), 'error');
    }


    /**
     * 导出
     */
    public function actionExport()
    {

        $header = [
            ['姓名', 'member.realname'],
            ['班次', 'attendClasses.title'],
            ['打卡类型', 'type', 'selectd', \addons\Attend\common\enums\CheckEnum::getMap()],
            ['打卡状态', 'state', 'selectd', \addons\Attend\common\enums\CheckStateEnum::getMap()],
            ['打卡时间', 'created_at', 'date', 'Y-m-d H:i:s'],
        ];
        $params= $SearchModel = Yii::$app->request->queryParams;
        unset($SearchModel['member_realname']);
        unset($SearchModel['attendClasses_title']);
        unset($SearchModel['created_at']);
        unset($SearchModel['type']);
        foreach ($SearchModel as $name => $value) {
            if( !$value )
                unset($SearchModel[$name] );
        }
//        Yii::$app->debris->p($SearchModel);

        $created_time = [];
        if(!empty($params['created_at'])){
            list($start,$end) = explode('/',$params['created_at']);
            $start = strtotime($start);
            $end = strtotime($end);
            $created_time = ['between',AttendCheck::tableName().'.created_at',$start,$end];
        }
//        Yii::$app->debris->p($created_time);

        $list = AttendCheck::find()->select('*')
            ->andWhere(['status' => StatusEnum::ENABLED,'merchant_id'=>Yii::$app->user->identity->merchant_id])
            ->andFilterWhere($SearchModel)
            ->andFilterWhere($created_time)
//            ->andFilterWhere(['realname'=>'系统管理员'])
            ->With(['member','attendClasses'])
            ->orderBy(AttendCheck::tableName().'.id DESC')
            ->asArray()
            ->all();
//        Yii::$app->debris->p($list);
        return ExcelHelper::exportData($list, $header);
    }
    protected function findModel($id)
    {
        if (empty($id) || empty(($model = $this->modelClass::findOne(['id' => $id, 'merchant_id' => $this->getMerchantId()])))) {
            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }
        return $model;
    }
}
